<?php

namespace App\Services\System;

use App\Common\Autoinject;
use App\Exceptions\ApiException;
use App\Http\Requests\System\SysLogin\LoginRequest;
use App\Services\BaseService;
use ruoyi\admin\constant\Constants;
use Illuminate\Support\Facades\Cache;
use App\Models\System\SysLogininforModel;
use App\Models\System\SysUserModel;
use ruoyi\admin\Utils;

class SysLoginService extends BaseService {

    public CaptchaService $captchaService;
    #[Autoinject]
    private SysLogininforModel $sysLogininforModel;
    #[Autoinject]
    private SysUserModel $userModel;

    public function __construct(CaptchaService $captchaService) {
        parent::__construct();
        $this->captchaService = $captchaService;
    }

    public function login(LoginRequest $request): string {
        $username = $request->get('username');
        $password = $request->get('password');
        $uuid = $request->get('uuid');        // config('admin.admin_catpcha')
        $code = $request->get('code');

        // 验证码
        $this->captchaService->validateCode($uuid, $code, fn($msg) => 
            $this->sysLogininforModel->recordLogininfor($username, Constants::LOGIN_FAIL, $msg)
        );
        // 账号状态
        $user = $this->userModel->selectUserByUsername2Status($username, fn($msg)=>
            $this->sysLogininforModel->recordLogininfor($username, Constants::LOGIN_FAIL, $msg)
        );
        // 密码
        PasswordService::validatePassword($user, $password, fn($msg)=>
            $this->sysLogininforModel->recordLogininfor($username, Constants::LOGIN_FAIL, $msg)
        );

        $this->sysLogininforModel->recordLogininfor($username, Constants::LOGIN_SUCCESS, '登录成功');
        $user->recordLastIp();
        return $user->createToken('admin_token')->plainTextToken;
    }

}
